# -*- coding: utf-8 -*-

from configuration import ConfigurationManager
from lib.pipuii18n import _

import sys

if sys.platform == 'linux2':
    from Tkinter import *
elif sys.platform == 'win32':
    from tkinter import *

import tkMessageBox

cmanager = ConfigurationManager()

class PreferencesWindow:
    
    master = None
    
    def __init__(self, root):
        self.master = Toplevel()
        self.master.transient(root)
        self.master.title(_(u"Preferences"))
        self.setupWidgets()
        self.bindEvents()
    
    def bindEvents(self):
        pass
        
    def setupWidgets(self):
        frame = Frame(self.master)
        self.master.rowconfigure(0, weight = 1)
        self.master.columnconfigure(0, weight = 1)
        frame.grid(row = 0, column = 0, sticky = N+S+E+W)

        frame.columnconfigure(0, weight = 2, pad = 40)
        frame.columnconfigure(1, weight = 1, pad = 40)
        frame.rowconfigure(0, weight = 1)
        frame.rowconfigure(1, weight = 1)
        
        lbl_language = Label(frame, text = _(u"Language"))
        self.lb_languages = Listbox(frame, selectmode = SINGLE)
        for i in sorted(cmanager['languages']):
            self.lb_languages.insert(END, i)
            if cmanager['language'] == cmanager['languages'][i]:
                self.lb_languages.select_set(END)
        
        lbl_language.grid(row = 0, column = 0, sticky = N+E+W+S, padx = 10, pady = 10)
        self.lb_languages.grid(row = 0, column = 1, sticky = N+E+W+S, padx = 10, pady = 10)

        # Setting up command buttons
        self.btn_OK = Button(frame, text = _(u"OK"), command = self.commandOK)
        self.btn_OK.grid(row = 1, column = 0, sticky = E+W+S, padx = 5, pady = 5)
        
        self.btn_cancel = Button(frame, text = _(u"Cancel"), command = self.commandCancel)
        self.btn_cancel.grid(row = 1, column = 1, sticky = E+W+S, padx = 5, pady = 5)
        

    def savePreferences(self):
        selection = self.lb_languages.curselection()
        if not selection:
            return
        selection = self.lb_languages.get(selection[0])
        for key, value in cmanager['languages'].items():
            if key == selection:
                cmanager['language'] = value
                cmanager.save()
                tkMessageBox.showinfo(_(u"Success"), _(u"Preferences successfully set. Changes are made after application restart."))
                return
        

    def commandCancel(self):
        self.master.withdraw()
    
    def commandOK(self):
        self.savePreferences()
        self.master.withdraw()
